package org.jeecg.zhenxuan.Controller;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.zhenxuan.CommonUtils.CommonUtils;
import org.jeecg.zhenxuan.Entity.Resources;
import org.jeecg.zhenxuan.Repository.ResourceRepository;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

@Controller
public class CommonAPIController {

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CommonAPIController.class);


    @Autowired
    private ResourceRepository resourceRepository;

    @ResponseBody
    @RequestMapping("/generateQRcode")
    public JSONObject generateQRcode(@RequestParam(required = true) String context, String size , @RequestParam(defaultValue = "Logo")String logo) {

        String base64Str = new String();
        if (logo.equals("Logo")) {
            try {
                base64Str = CommonUtils.crateQRCodeForBase64(context, 500, 500);
            } catch (IOException e) {
                e.printStackTrace();
                log.error(e.toString());
            }

        }else{

                String note = "";
                log.info("生成带Logo二维码：logo地址为 /usr/local/logo/"+ logo);
                File logoFile = new File("/usr/local/logo/"+logo);//logo图片路径
                base64Str = CommonUtils.drawLogoQRCode(logoFile, context, note);

        }

      /*  RestTemplate restTemplate = new RestTemplate();
        String qrCodeHtml = restTemplate.getForObject("https://cli.im/api/qrcode/code?text={1}",
                String.class
                ,context);
        String regexImage = "<img.+?src=\"(.+?)\".+?/?>";
        String ImageSrcStr="";
        String base64Str="";
        Pattern p = Pattern.compile(regexImage,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(qrCodeHtml);
        if(m.find()){
            // src代码段
            ImageSrcStr = m.group(1);
            try {
                String temp = CommonUtils.encodeImageToBase64(new URL("http:" + ImageSrcStr));
                if (org.apache.commons.lang.StringUtils.isNotBlank(temp)) {
                    Pattern pr = Pattern.compile("\\s*|\t|\r|\n");
                    Matcher mr = pr.matcher(temp);
                    base64Str = mr.replaceAll("");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "T");
        jsonObject.put("context", base64Str);

        return jsonObject;
    }

    @ResponseBody
    @RequestMapping("/addResource")
    public JSONObject addResourceProc(Resources resources) {
        JSONObject result = new JSONObject();
        if (resources == null || resources.getContext().isEmpty() || resources.getName().isEmpty()) {
            result.put("status", "F");
            result.put("information", "参数为空！");
            return result;
        }

        Resources temp = resourceRepository.save(resources);

        if (temp == null || temp.getContext().isEmpty() || temp.getName().isEmpty()) {
            result.put("status", "F");
            result.put("information", "资源添加失败！");
            return result;
        }
        result.put("id", temp.getId());
        result.put("context", temp.getContext());
        return result;
    }

    @ResponseBody
    @RequestMapping("/getResourceByName")
    public JSONObject getResourceByNameProc(String name){
        JSONObject result = new JSONObject();
        if (name == null || name.isEmpty()) {
            result.put("status", "F");
            result.put("information", "参数为空！");
        }

        Resources resources = resourceRepository.getResourcesByName(name);

        if (resources == null || resources.getContext().isEmpty()) {
            result.put("status", "F");
            result.put("information", "资源为空！");
        }
        result.put("id", resources.getId());
        result.put("context", resources.getContext());

        return result;
    }

    /**
     * generate signature
     * add by 2019年11月19日 星期二
     */
    /**
     * generate signature
     * add by 2019年11月19日 星期二
     * @param secret
     * @param signatureAlgorithm
     * @param expirationMillisecond
     * @param headers
     * @param claims
     * @return
     */
    @ResponseBody
    @RequestMapping("/generateJwtSignature")
    public String generateJwtSignatureProc(String secret, SignatureAlgorithm signatureAlgorithm, Long expirationMillisecond, String headers, String claims) {
        /**
         * add by 2019年11月21日 星期四
         * begin
         */
        if (StringUtils.isEmpty(secret) || expirationMillisecond == null || expirationMillisecond == 0) {
            log.error("生成JWT验签：参数为空！");
            return "参数为空！";
        }

        /**
         * add end
         */

        String claimsStr = new String();
        try {
            claimsStr = URLDecoder.decode(claims, "utf8");
//            claimsStr = URLDecoder.decode(claims, "utf8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Map<String,String> claimsTemp = JSONObject.parseObject(claimsStr, Map.class);
        Map<String,String> headerTemp = JSONObject.parseObject(headers, Map.class);
        return CommonUtils.generateJWT(secret, SignatureAlgorithm.HS384, expirationMillisecond, headerTemp, claimsTemp);
    }

    /**
     * add by 2019年11月19日 星期二
     * 翻译signature
     */

    /**
     * add by 2019年11月19日 星期二
     * 翻译signature
     * @param jwts
     * @param secret
     * @param signatureAlgorithm
     * @param expirationMillisecond
     * @return
     */
    @ResponseBody
    @RequestMapping("/translateJwtSignature")
    public JSONObject translateJwtSignatureProc(String jwts, String secret, SignatureAlgorithm signatureAlgorithm, Long expirationMillisecond) {
        /**
         * add by 2019年11月21日 星期四
         * begin
         */

        if (StringUtils.isEmpty(secret) || StringUtils.isEmpty(jwts)) {
            log.error("生成JWT验签：参数为空！");
            JSONObject result = new JSONObject();
            result.put("status", "生成JWT验签：参数为空！");

            return result;
        }

        /**
         * add end
         */
        Claims claims = CommonUtils.translateJWT(jwts, secret, SignatureAlgorithm.HS384, expirationMillisecond);

        String jsonstr = JSONObject.toJSONString(claims);
        return JSONObject.parseObject(jsonstr);
    }
}

